package mirkofrancuski.battleship;

import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;

public class SettingsActivity extends PreferenceActivity implements
		OnSharedPreferenceChangeListener {

	public static final String KEY_PREF_USERNAME = "pref_username";
	public static final String KEY_PREF_COMPUTER_PLAYER = "pref_computerPlayer";

	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.preferences);
	}

	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
			String key) {
		updatePreference(sharedPreferences, key);
	}
	
	@SuppressWarnings("deprecation")
	private void updatePreference(SharedPreferences sharedPreferences,
			String key){
		if (key.equals(KEY_PREF_USERNAME)) {

			Preference preference = findPreference(key);
			// Set summary to be the user-description for the selected value
			String username = sharedPreferences.getString(key, "");
			if(username.equals(""))
				username = getResources().getString(R.string.pref_username_default);
			preference.setSummary(username);
		}
		if (key.equals(KEY_PREF_COMPUTER_PLAYER)) {
			Preference preference = findPreference(key);
			// Set summary to be the user-description for the selected value
			preference.setSummary(sharedPreferences.getString(key, ""));
			
		}
	}

	@SuppressWarnings("deprecation")
	@Override
	protected void onResume() {
		super.onResume();
		SharedPreferences sharedPreferences = getPreferenceScreen().getSharedPreferences();
		sharedPreferences.registerOnSharedPreferenceChangeListener(this);
		updatePreference(sharedPreferences, KEY_PREF_USERNAME);
		updatePreference(sharedPreferences, KEY_PREF_COMPUTER_PLAYER);
				
	}

	@SuppressWarnings("deprecation")
	@Override
	protected void onPause() {
		super.onPause();
		getPreferenceScreen().getSharedPreferences()
				.unregisterOnSharedPreferenceChangeListener(this);
	}

}
